package com.example.mq.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Component
public class LoggerInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        HandlerMethod method = (HandlerMethod) handler;
//        //方法名
//        String name = method.getMethod().getName();
//        //类名
//        String allname = method.getBean().getClass().getName() + ":" + name;
//        logger.info("Api开始调用,调用地址" + allname );
        request.setAttribute("start_time", System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod method = (HandlerMethod) handler;
            //方法名
            String name = method.getMethod().getName();
            //类名
            String allname = method.getBean().getClass().getName() + ":" + name;
            if (response.getStatus() == 200) {
                logger.info("Api调用成功,调用地址" + allname + ", 调用耗时:"+ String.valueOf(System.currentTimeMillis()-(long)request.getAttribute("start_time"))+"ms");
                return;
            }
            logger.error("Api调用失败, 地址:"+allname);
        }else{
            logger.error("非HandleMethods请求, 请求类型:"+handler);
        }
        SecurityContextHolder.clearContext();
    }
}
